const userListEle = document.querySelector('#user-list') //tbody
const baseUrl = "http://47.105.173.95:3000/api/users"

function ajaxGet(url, callback) {
    //#1.创建xhr实例
    const xhr = new XMLHttpRequest()
    //#2.初始化一个请求
    xhr.open('GET', url)
    //#3.发送请求
    xhr.send()
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            callback(res)
        }
    }
}


function initUsers() {
    ajaxGet(baseUrl, function (res) {
        // console.log(res)
        const users = res.results.users
        // console.log(users)
        renderUserList(users)
    })
}

function renderUserList(users) {
    // let html = ''
    // for (let i = 0; i < users.length; i++) {
    //     let user = users[i]
    //     let trHtml = `
    //     <tr>
    //         <th>${user.id}</th>
    //         <th>${user.username}</th>
    //         <th>${user.gender == 0 ? '男' : '女'}</th>
    //         <th>${user.telephone}</th>
    //         <th>${user.email}</th>
    //         <th>
    //             <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-detail" data-id=${user.id} data-type="detail">详细</button>
    //             <button type="button" class="btn btn-danger btn-sm" data-id=${user.id} data-type="delete">删除</button>
    //         </th>
    //     </tr>`
    //     html += trHtml
    // }
    const html = users.map(user => {
        return `
            <tr>
                <th>${user.id}</th>
                <th>${user.username}</th>
                <th>${user.gender == 0 ? '男' : '女'}</th>
                <th>${user.telephone}</th>
                <th>${user.email}</th>
                <th>
                    <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-detail" data-id=${user.id} data-type="detail">详细</button>
                    <button type="button" class="btn btn-danger btn-sm" data-id=${user.id} data-type="delete">删除</button>
                </th>
            </tr>`
    }).join('')
    userListEle.innerHTML = html


}

function getUser(id, callback) {
    const url = baseUrl + `?id=${id}`
    ajaxGet(url, function (res) {
        if (res.code == 0) {
            const user = res.results.users[0]
            callback(user)
        } else {
            alert(res.msg)
        }
    })
}


userListEle.addEventListener('click', function (e) {
    const clickElement = e.target
    if (clickElement.tagName == 'BUTTON') {
        if (clickElement.dataset.type == 'detail') {
            //点击的是详细按钮
            const id = clickElement.dataset.id //获取点击的详细按钮对应的id
            getUser(id, function (user) {
                console.log(user)
                renderUserDetail(user)

            })

        } else if (clickElement.dataset.type == 'delete') {
            //删除操作
            //TODO
        }
    }
})

// const usernameIpt = document.getElementById('username')
// const emailIpt = document.getElementById('email')

// function renderUserDetail(user){
//     usernameIpt.value = user.username
//     emailIpt.value = user.email
// }

//详细信息表单字段---选择器
const detailFormFieldSelector = {
    username: '#username',
    email: '#email',
    nickname:"#nickname",
    telephone: '#telephone',
    birthday: '#birthday',
    gender: "[name=gender]",
    state: "#state",
    addr: "#addr",
    loginTime: "#login-time",
    intro: "#intro"
}
//详细信息表单字段---元素
const detailFormFieldElement = {}
//详细信息表单字段---返回user的键
const detailFormFieldKey = {
    username: "username",
    email: "email",
    nickname:"nicheng",
    telephone: "telephone",
    birthday: "birthday",
    gender: "gender",
    state: "state",
    addr: "address",
    loginTime: "time",
    intro: "intro"
}
//把所有字段对应的输入框找到并挂载到detailFormFieldElement里面
function initDetailFormElement() {
    for (let field in detailFormFieldSelector) {
        const selector = detailFormFieldSelector[field]
        detailFormFieldElement[field] = document.querySelector(selector)
    }
}
initDetailFormElement()

//把用户的数据渲染到用户详细页面表单
function renderUserDetail(user) {
    //详细信息表单字段---值
    for (let field in detailFormFieldElement) {
        const element = detailFormFieldElement[field]
        const fieldKey = detailFormFieldKey[field]
        const fieldValue = user[fieldKey]
        element.value = fieldValue
    }
}



initUsers()

/*
 触发点击事件 -> 请求数据 -> 拿到返回的数据并解析 -> 渲染到网页
*/